import axios from 'axios';

// 通用公用方法
const req = (method, url, params) => {
    // 增加公共参数
    if (url.indexOf('?') == -1) {
        // url = url + '?userid='+(localStorage.getItem('userid')?localStorage.getItem('userid'):"");
        url = url + '?userid=13375398311'
    } else {
        // url = url + '&userid='+(localStorage.getItem('userid')?localStorage.getItem('userid'):"");
        url = url + '&userid=13375398311'
    }
    return axios({
        method: method,
        url: url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: params,
        traditional: true,
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret +=
                        encodeURIComponent(it) +
                        '=' +
                        encodeURIComponent(data[it]) +
                        '&'
                }
                return ret
            }
        ]
    }).then(res => res.data);
};
// 图片上传
const upimgdata = (file) => {
    let formData = new FormData()
    formData.append('file', file);
    return axios({
        method: 'post',
        url: '/Home/Index/uploads',
        headers: {
            'Content-Type': "multipart/form-data;charset=utf-8",
        },
        data: formData,
    }).then(res => res.data)
};
const localStorageSet = (name, data, expire = 24) => {
    const time = new Date().getTime() + expire * 60 * 60 * 1000;
    const obj = { data, time };
    localStorage.setItem(name, JSON.stringify(obj));
};
const localStorageGet = name => {
    const storage = localStorage.getItem(name);
    const time = new Date().getTime();
    let result = {};
    if (storage) {
        const obj = JSON.parse(storage);
        if (time < obj.time) {
            result = obj.data;
        } else {
            localStorage.removeItem(name);
        }
    }
    return result;
};
export {
    req,
    upimgdata,
    localStorageSet,
    localStorageGet,
}